package com.Exam;

import java.lang.module.FindException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class Exam02 {
    //使⽤线程池实现⼀个简单的⽣产者-消费者模型，其中有多个⽣产者和多个消费者。
    public static void main(String[] args) {
        int numProduce = 3;
        int numConsumer = 2;
        int bufferSize = 5;
        ExecutorService executorService = Executors.newFixedThreadPool(numProduce + numConsumer);
        BlockingDeque<Integer> block = new LinkedBlockingDeque<>(bufferSize);
        for (int i = 0; i < numProduce; i++) {
            executorService.execute(new ProduceRunnable(block));
        }
        for (int i = 0; i < numConsumer; i++) {
            executorService.execute(new ConsumerRunnable(block));
        }
        executorService.shutdown();
    }
}
class ConsumerRunnable implements Runnable{
    private BlockingDeque<Integer> buffer;
    public ConsumerRunnable(BlockingDeque<Integer> buffer) {
        this.buffer = buffer;
    }
    @Override
    public void run() {
        try {
            while (true){
                int item = (int)(Math.random() *100);
                buffer.put(item);
                System.out.println(Thread.currentThread().getName() + "生产了：" + item);
                Thread.sleep(1000);
            }
        }catch (InterruptedException e){
            Thread.currentThread().interrupt();
        }

    }
}
class ProduceRunnable implements Runnable{
    private BlockingDeque<Integer> buffer;
    public ProduceRunnable(BlockingDeque<Integer> buffer) {
        this.buffer = buffer;
    }
    @Override
    public void run() {
        try {
            while (true){
                int item = buffer.take();
                System.out.println(Thread.currentThread().getName() + "消费：" + item);
                Thread.sleep(1000);
                }
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}